<template>
    <Dialog :title="dialogTitle" v-model="dialogVisible">
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px" v-loading="formLoading">
            <el-form-item label="班级名称" prop="gradeName">
                <el-input v-model="formData.gradeName" placeholder="请输入班级名称" />
            </el-form-item>
            <el-form-item label="拼团选择" prop="applyId">
                <el-select v-model="formData.applyId" placeholder="请选择拼团" @change="handleChangeApply">
                    <el-option v-for="item in applyList" :label="`${item.spuName} - ${item.address}`" :value="item.id" :key="item.id" />
                </el-select>
            </el-form-item>
            <el-form-item label="教练" prop="coachId">
                <el-select v-model="formData.coachId" placeholder="请选择教练" @change="handleChangeUser">
                    <el-option v-for="item in userList" :key="item.id" :label="item.nickname" :value="item.id" />
                </el-select>
            </el-form-item>
            <!-- <el-form-item label="上课地址" prop="gradeAddress">
                <el-input v-model="formData.gradeAddress" readonly placeholder="请点击选择门店地址" @click="handleSelectAddress" />
            </el-form-item> -->
        </el-form>
        <template #footer>
            <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
        </template>

        <!-- <el-dialog v-model="showAddressSelect" title="地址选择" width="60%" :close-on-click-modal="false" :append-to-body="true">
            <iframe id="mapPage" width="100%" height="600px" frameborder=0
                src="https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=JXWBZ-2CX34-OPOU2-DECPC-PN47J-57BQI&referer=javascript_map">
            </iframe>
        </el-dialog> -->
    </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import * as ClassApi from '@/api/mall/class'
import * as CombinationRecordApi from '@/api/mall/promotion/combination/combinationRecord'
import * as UserApi from '@/api/system/user'
import * as CombinationApplyApi from '@/api/mall/promotion/combination/combinationApply'

defineOptions({ name: 'ClassForm' })

const getForm = () => {
    return {
        /**
         * 班级ID
         */
        id: '',
        /**
         * 开团记录ID
         */
        applyId: '',
        /**
         * 班级名称
         */
        gradeName: '',
        /**
         * 班级管理员 团长ID
         */
        adminId: '',
        /**
         * 班级管理员 团长姓名
         */
        gradeAdmin: '',
        /**
         * 上课教练ID
         */
        coachId: '',
        /**
         * 上课教练名称
         */
        gradeCoach: '',
        /**
         * 上课地点
         */
        gradeAddress: '',
        /**
         * 纬度
         */
        latitude: '',
        /**
         * 经度
         */
        longitude: '',
        /**
         * 课程配置信息 对应开团信息中的skuProperties
         */
        courseProperties: []
    }
}

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref(getForm())
const showAddressSelect = ref(false) // 地址选择弹窗
/** 表单 Ref */
const formRef = ref()
/** 表单校验规则 */
const formRules = reactive({
    gradeName: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
    applyId: [{ required: true, message: '拼团不能为空', trigger: 'change' }],
    coachId: [{ required: true, message: '教练不能为空', trigger: 'change' }],
    gradeAddress: [{ required: true, message: '上课地址不能为空', trigger: 'change' }]
})

/** 打开弹窗 */
const open = async (type: string, id ? : number) => {
    dialogVisible.value = true
    dialogTitle.value = t('action.' + type)
    formType.value = type
    resetForm()
    // 修改时，设置数据
    if (id) {
        formLoading.value = true
        try {
            // formData.value = await ProductBrandApi.getBrand(id)
        } finally {
            formLoading.value = false
        }
    }
    getApplyList();
    getAllUser();
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
    // 校验表单
    if (!formRef) return
    const valid = await formRef.value.validate()
    if (!valid) return
    // 提交请求
    formLoading.value = true
    try {
        const data = formData.value as ClassApi.ClassVO
        await ClassApi.createOrUpdateClass(data)
        if (formType.value === 'create') {
            message.success(t('common.createSuccess'))
        } else {
            message.success(t('common.updateSuccess'))
        }
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
    } finally {
        formLoading.value = false
    }
}

/**======== 拼团 -start ========*/
const applyList = ref([]);
/** 查询列表 */
const getApplyList = async () => {
    try {
        const data = await CombinationApplyApi.getCombinationApplyPage({
            pageSize: 100,
            pageNo: 1,
            status: 2
        })
        applyList.value = data.list
    } finally {
        
    }
}
/**
 * 选择拼团，设置课程配置信息
 */
const handleChangeApply = (value) => {
    let item = applyList.value.find(item => item.id == value);

    if (!item) {
        return;
    }

    formData.value.courseProperties = item.skuProperties;
    formData.value.adminId = item.userId;
    formData.value.gradeAdmin = item.nickname;

    formData.value.gradeAddress = item.address;
    formData.value.latitude = item.latitude + '';
    formData.value.longitude = item.longitude + '';
}
/**======== 拼团 -end ========*/

/**======== 教练 -start ========*/
const userList = ref<UserApi.UserVO[]>([]);
/** 查询所有用户列表 */
const getAllUser = () => {
    UserApi.getUserPage({
        pageNo: 1,
        pageSize: 100
    }).then(res => {
        userList.value = res.list as UserApi.UserVO[];
    })
}
const handleChangeUser = (value) => {
    let item = userList.value.find(item => item.id == value);

    if (!item) {
        return;
    }

    formData.value.gradeCoach = item.nickname;
}
/**======== 教练 -end ========*/

/**======== 地址选择 -start ========*/
const getLocation = (event) => {
    // 接收位置信息，用户选择确认位置点后选点组件会触发该事件，回传用户的位置信息
    var loc = event.data;
    // 防止其他应用也会向该页面post信息，需判断module是否为'locationPicker'
    if (loc && loc.module == 'locationPicker') {
        showAddressSelect.value = false;
        formData.value.gradeAddress = loc.poiaddress;
        formData.value.latitude = loc.latlng.lat + '';
        formData.value.longitude = loc.latlng.lng + '';
    }
}

const handleSelectAddress = () => {
    showAddressSelect.value = true;
}
/**======== 地址选择 -end ========*/

/** 重置表单 */
const resetForm = () => {
    formData.value = getForm();
    formRef.value?.resetFields()
}

/** 初始化 */
onMounted(async () => {
    window.addEventListener('message', getLocation, false);
})

onUnmounted(() => {
    window.removeEventListener('message', getLocation, false);
})

</script>
